<template>
  <div>
    <!-- 全局header -->
    <sm-head :page-type="getTitleStr(searchKey.content_type)" ref="head" :fix-head="true"></sm-head>
    <section id="page">
      <!-- 更新信息 -->
        <div class="info-tip" v-show="tipShow">
          {{tip}}
        </div>
        <ul class="jokes-list">
          <li v-for="(item,index) in jokesFilter" v-if="item.group" :key="item">
            <div class="user-info" :style="{paddingLeft: item.group.is_neihan_hot?'0':'10px'}">
              <div class="hot-wrap" v-if="item.group.is_neihan_hot">
                  <span>热门</span>
              </div>
              <img class="user-avatar" :src="item.group.user.avatar_url">
              <div class="user-name">{{item.group.user.name}}</div>
              <div class="icon-close" @click="deleteJoke(index)" @touchend="deleteJoke(index)">&times;</div>
            </div>
            <!-- 内容 -->
            <div class="nh-content">
              <div class="nh-content-wrapper">
                {{item.group.content}}
                <div class="nh-bar-link">
                  <div class="link-text">
                    <span>{{item.group.category_name}}</span>
                  </div>
                </div>
              </div>
              <!-- 假如有视频存在 -->
              <div v-if="item.group.is_video && item.group.is_video == 1">
                <d-player :video="item.group.videoPlayer" :autoplay="autoplay" :loop="loop">
                </d-player>
              </div>
              <!-- gif视频 -->
              <div v-if="item.group.is_gif && item.group.is_gif == 1">
                <d-player :video="item.group.gifPlayer" :autoplay="autoplay" :loop="loop">
                </d-player>
              </div>
              <!-- 爆笑囧图 一张-->
              <div class="preview-wrapper" style="max-height:632px;" v-if="item.group.media_type && item.group.media_type == 1">
                <img class="preview-img nh-pic" :src="item.group.thumbOne" @click="thumbClick(item.group)">
                <div class="long-img-bg" v-if="item.group.middle_image.height>1000" @click="thumbClick(item.group)">
                  <span>点击查看长图</span>
                </div>
              </div>
              <!-- 爆笑囧图 多张-->
              <div class="thumb-list" v-if="item.group.thumb_image_list">
                <img class="preview-img thumb-item nh-pic" v-for="(thumb, index) in item.group.thumb_image_list" :key="index" :src="thumb.url"
                  @click="thumbListClick(index, item.group.large_image_list)">
              </div>

              <!-- footer 点赞评论分享 -->
              <ul class="action-btn-list">
                <li class="btn digg-item" @click="click_up(item.group.up_id.up_id)" :id="item.group.up_id.up_id">
                  <span class="up">{{item.group.digg_count}}</span>
                </li>
                <li class="btn bury-item" @click="click_down(item.group.down_id.down_id)" :id="item.group.down_id.down_id">
                  <span class="down">{{item.group.bury_count}}</span>
                </li>
                <li class="btn comment-item">
                  <span>{{item.group.comment_count}}</span>
                </li>
                <li class="btn share-item" @click="shareOpen(item.group.text,item.group.cover_image_uri,item.group.share_url)">
                  <span>{{item.group.share_count}}</span>
                </li>
              </ul>

            </div>
          </li>
        </ul>
        <!-- 加载更多 -->
        <div class="loadMore" v-if="loadMore">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span> 数据加载中...
        </div>
        <!-- 分享 -->
        <sm-share v-if="shareFlag" :share-open="shareFlag" :share-title="shareText" :share-pic="shareImageUri" :share-url="shareUrl"
          @shareClose="shareClose">
        </sm-share>
        <!-- 刷新 -->
        <div class="refresh-btn-wrapper">
          <span class="refresh-btn" :class="{spinner: refreshFlag}" @click="refreshPage"></span>
        </div>
      </section>
  </div>
</template>
<script>
import $ from 'webpack-zepto'
import smHeader from '@/components/header'
import smShare  from '@/components/share'
import VueDPlayer from 'vue-dplayer'
import utils from '@/libs/utils'

require('../assets/scss/index.scss')

export default{
  name: 'sm-list',
  components: {
    'd-player': VueDPlayer,
    'sm-head': smHeader,
    'sm-share': smShare
  },
  data(){
    return{
      scroll: true,
      searchKey: {
          essence: 1,               // 固定值 1
          content_type: -101,       // 从获取 content_type 中获取得到的 list_id 字段值。目前推荐的是-101，视频的是-104，段友秀的是-301，图片的是-103，段子的是-102
          iid: 9234212697,          // 一个长度为10的纯数字字符串，用于标识用户唯一性
          os_version: "10.3.1",     // 操作系统版本号，例如7.1.0
          os_api: 18,               // 操作系统版本，例如20
          app_name: "joke_essay",   // 固定值joke_essay
          channel: "App Store",     // 下载渠道，可360、tencent等
          device_platform: "iphone", // 设备平台，android 或 ios
          idfa: "C1A098F7-F4FD-4637-8ADD-C2E80284C0D8", //
          live_sdk_version: 130,
          vid:                      "60557D26-38D4-44D4-AE1B-3B8573EA465C",
          openudid:                 "06c3fa553c55ede174948ed86a46958580c7bde6", // 一个长度为16的数字和小写字母混合字符串
          device_type: "iPhone 6", // 设备型号，例如 hongmi
          version_code: "6.1.5",
          ac: "WIFI",               // 网络环境，可取值 wifi
          screen_width: "750",      // 屏幕宽度，px为单位
          device_id: "35453050449",
          aid: "7",                 // 固定值7
          city: "上海",
          count: 30,                // 返回数量
          double_col_mode: 0,
          latitude: 31.22186538475997, // 经度。可为空
          longitude: 121.4848468443627, // 纬度。可为空
          message_cursor: 0,
          mpic: 1
      },
      jokes: [],
      autoplay: false,
      loop: false,
      loadMore: false,
      shareFlag: false,
      shareText: '',
      shareImageUri: '',
      shareUrl: '',
      refreshFlag : false,
      tip: '',
      tipShow: false
    }
  },
  mounted() {
      window.scrollTo(0, 0);
      this.tip = '';
      if (this.$route.query && this.$route.query.tags) {
          this.searchKey.content_type = this.$route.query.tags;
      }
      this.getLists(true);
      // 滚动加载
      $(window).on('scroll', utils.throttle(this.getScrollData, 300, 1000));
  },
  methods: {
    click_up(id){
      // $('#'+id).find('span').css("background-url", "url('http://s3.bytecdn.cn/neihan/resource/neihan_reflow/neihan_common/static/image/detail/digg_ed_0b1c5ec.png')")
      // var tmp = $('.digg-item')
      var tmp = $('#'+id).find('span')
      if(tmp.hasClass('up')){
        tmp.removeClass('up').addClass('up_hot')
        tmp.text(parseInt(tmp.text()) + 1)
      }
    },
    click_down(id){
      var tmp=$('#'+id).find('span')
      if(tmp.hasClass('down')){
        tmp.removeClass('down').addClass('down_hot')
        tmp.text(parseInt(tmp.text()) - 1)
      }
    },
    // 获取title文字
    getTitleStr(tags) {
        let str = '';
        switch (tags) {
            case '-101':
                str = '推荐';
                break;
            case '-104':
                str = '视频';
                break;
            case '-301':
                str = '段友秀';
                break;
            case '-103':
                str = '图片';
                break;
            case '-102':
                str = '段子';
                break;
            default:
                str = '推荐';
                break;
        }
        return str;
    },
    // 获取数据
    getLists(bool) {
      this.axios.get('neihan/stream/mix/v1/', this.searchKey)
        .then((response) => {
            let data = response.data.data;
            this.scroll = true;
            this.refreshFlag = false;
            // this.tipShow = response.has_new_message;
            // this.tipShow  = true
            this.loadMore = response.data;
            if (data) {
                if (bool) {
                    this.tip = data.tip;
                    this.jokes = this.jokes.concat(data.data)
                } else {
                    this.tip = data.tip;
                    this.jokes = data.data;
                }
            } else {
                this.refreshFlag = true;
                setTimeout(() => {
                    bool ? this.getLists(true) : this.getLists(false);
                }, 3000);
            }
        }, (error) => {
            console.log(error)
        });
    },
    // 滚动加载数据
    getScrollData() {
        if (this.scroll) {
            let totalheight = $(window).height() + $(window).scrollTop();
            if ($(document).height() <= totalheight + 300) {
                this.scroll = false;
                this.refreshFlag = true;
                this.getLists(true);
            }
        }
    },
    // 单图预览
    thumbClick(item) {
        this.$preview.open(0, [{
            w: item.large_image.width,
            h: item.large_image.height,
            src: item.large_image.url_list["0"].url
        }]);
    },
    // 多图预览
    thumbListClick(index, list) {
        let arr = [];
        arr = list.map(function(item, index) {
            return Object.assign({}, item, {
                w: item.width,
                h: item.height,
                src: item.url
            });
        });
        this.$preview.open(index, arr, {
            captionEl: true,
            fullscreenEl: true,
            history: true,
            shareEl: false,
            tapToClose: true
        });
    },
    // 删除单条
    deleteJoke(index) {
        this.jokesFilter.splice(index, 1)
    },
    // 分享
    shareOpen(text, imageUrl, linkUrl) {
      this.shareFlag = true
      this.shareText = text
      this.shareImageUri = imageUrl ? 'http://p1.pstatp.com/large/' + imageUrl : ''
      this.shareUrl  = linkUrl
    },
    // 取消分享
    shareClose() {
        this.shareFlag = false
    },
    // 刷新并返回顶部
    refreshPage() {
        window.scrollTo(0, 0)
        this.refreshFlag = true
        this.tipShow = true
        this.getLists(false)
    }
  },
  computed: {
      jokesFilter: function() {
          let jokesNew = this.jokes.map((item, index) => {
              if (item.group && item.group.is_video && item.group.is_video == 1) {

                  let videoUrl = '';
                  if (item.group.hasOwnProperty('mp4_url')) {
                      videoUrl = item.group.mp4_url;
                  } else {
                      videoUrl = 'http://ic.snssdk.com/neihan/video/playback/?video_id=481c0048fb3c48e4ab9f8f2619e0a299&quality=480p&line=0&is_gif=0&device_platform=iphone.mp4'
                  }
                  // console.log(videoUrl + '--video->>' + '--' + item.group.medium_cover.url_list['0'].url + item.group.text)
                  item.group.videoPlayer = {
                      url: videoUrl,
                      pic: item.group.medium_cover.url_list[0].url
                  }
              }
              if (item.group && item.group.is_gif && item.group.is_gif == 1 && item.group.gifvideo) {
                  let gifUrl = '';
                  if (item.group.gifvideo.hasOwnProperty('mp4_url')) {
                      gifUrl = item.group.gifvideo.mp4_url;
                  } else {
                      gifUrl = 'http://ic.snssdk.com/neihan/video/playback/?video_id=a3c0bfb31958474c80b5acbf921f1622&quality=480p&line=0&is_gif=1&device_platform=None.mp4'
                  }
                  item.group.gifPlayer = {
                      url: gifUrl,
                      pic: item.group.middle_image.url_list[0].url
                  }
              }
              if (item.group && item.group.media_type && item.group.media_type == 1) {
                  item.group.thumbOne = item.group.middle_image.url_list[0].url
              }
              item.group.up_id = {
                  up_id: item.group.id+'-up'
              }
              item.group.down_id = {
                  down_id: item.group.id+'-down'
              }
              return item;
          });
          this.jokes = jokesNew.filter(function(item, index) {
              return !item.ad;
          });
          return this.jokes;
      }
  },
  watch: {
    // 切换页面
    '$route' (to, from) {
        // 如果是当前页面切换分类的情况
        if (to.query && to.query.tags) {
            this.searchKey.content_type = to.query.tags;
            this.jokes = [];
            this.loadMore = true;
        }
        this.getLists(true);
        // 隐藏导航栏
        this.$refs.head.show = false;
    }
  },
}
</script>
